<template>
  <div style="margin: 0 auto;">
    <canvas ref="canvas" style="width:500px;height:30px;position: absolute;bottom: 40px;margin-left: -250px;"></canvas>
  </div>
</template>

<script>
export default {
  data() {
    return {
      audioContext: null,
      analyser: null,
      microphone: null,
      dataArray: null,
      isRecording: false,
      recognition: null,
      animationId: null,
    };
  },
  methods: {
    async startRecording() {
      // 初始化音频上下文和分析器
      this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
      this.analyser = this.audioContext.createAnalyser();
      this.analyser.fftSize = 2048;

      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        this.microphone = this.audioContext.createMediaStreamSource(stream);
        this.microphone.connect(this.analyser);

        this.dataArray = new Uint8Array(this.analyser.frequencyBinCount);
        this.isRecording = true;

        this.drawWaveform(); // 开始绘制声波
        // this.recognition.start(); // 启动语音识别
      } catch (error) {
        console.error('无法访问麦克风:', error);
      }
    },

    stopRecording() {
      if (this.microphone) {
        this.microphone.disconnect();
        this.audioContext.close();
        // this.recognition.stop(); // 停止语音识别
      }

      cancelAnimationFrame(this.animationId);
      this.isRecording = false;
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext('2d');
      ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布
    },

    drawWaveform() {
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext('2d');

      ctx.fillStyle = '#202735';
      ctx.fillRect(0, 0, canvas.width, canvas.height); // 清空画布

      this.analyser.getByteTimeDomainData(this.dataArray); // 获取音频数据

      ctx.lineWidth = 8;
      // 创建线性渐变
      const gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
      gradient.addColorStop(0, '#ff7675'); // 起点：红色
      gradient.addColorStop(0.5, '#199efc'); // 中间：蓝色
      gradient.addColorStop(1, '#f1c40f'); // 终点：黄色
      ctx.strokeStyle = gradient; // 使用渐变色
      ctx.beginPath();

      const sliceWidth = canvas.width / this.dataArray.length;
      let x = 0;

      for (let i = 0; i < this.dataArray.length; i++) {
        const v = this.dataArray[i] / 128.0; // 将数据范围标准化
        const y = v * (canvas.height / 2); // 转换为绘图坐标

        if (i === 0) {
          ctx.moveTo(x, y);
        } else {
          ctx.lineTo(x, y);
        }

        x += sliceWidth; // 增加 x 坐标
      }

      ctx.lineTo(canvas.width, canvas.height / 2); // 结束路径
      ctx.stroke();

      this.animationId = requestAnimationFrame(this.drawWaveform); // 循环调用
    },
  },
};
</script>

<style scoped>
h1 {
  font-size: 2em;
  margin-bottom: 20px;
}

button {
  margin: 5px;
  padding: 10px;
}

/* canvas {
  border: 1px solid black;
} */
</style>